package com.olda.play.storage;

import com.olda.play.constant.Constant;
import com.olda.play.redis.RedisUtil;
import com.qiniu.util.Auth;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 */
@Component
public class QiNiuUtil {

    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    @Value("${qiniu.bucket}")
    private String bucket;

    @Value("${bill.change.lock.prefix}")
    private String billChangeLockPrefix;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedissonClient redissonClient;


    public String getQiNiuToken(){
        Auth auth = Auth.create(accessKey, secretKey);
        /**
         * 参考文案
         * https://github.com/qiniu/java-sdk/blob/master/src/main/java/com/qiniu/util/Auth.java
         * https://developer.qiniu.com/kodo/manual/1206/put-policy
         */
        if(redisUtil.hasKey(Constant.KEY_QINIU_TOKEN)){
            return redisUtil.get(Constant.KEY_QINIU_TOKEN);
        }
        String upToken = auth.uploadToken(bucket,null,86400L,null);//TODO  token 24小时有效
        redisUtil.set(Constant.KEY_QINIU_TOKEN,upToken);
        return upToken;
    }

    public String getQiNiuTokenRedisson(){
        String key=Constant.KEY_QINIU_TOKEN;
        Auth auth = Auth.create(accessKey, secretKey);
        RLock lock = redissonClient.getLock(billChangeLockPrefix + key);
        try {
            lock.lock(30, TimeUnit.SECONDS);
            if(redisUtil.hasKey(Constant.KEY_QINIU_TOKEN)){
                return redisUtil.get(Constant.KEY_QINIU_TOKEN);
            }
            String upToken = auth.uploadToken(bucket,null,86400L,null);//TODO  token 24小时有效
            redisUtil.set(Constant.KEY_QINIU_TOKEN,upToken);
            return upToken;
        } catch (Exception e) {
//            throw new Exception("异常：" + ExceptionUtils.getStackTrace(e));
            throw e;
        } finally {
            lock.unlock();
        }
    }



}
